import _ from "lodash";
import Config from "../config.js";
import Upload from "./upload.js";
import Util from "./util.js";

/**
 * 用户相关工具类
 */
var user = _.extend({}, _, {
    /**
     * 获取用户的头像，先检查本地，本地没有则从服务器下载
     * @param {*} user 用户信息，包含用户id和用户头像路径
     * @param {*} gotCallback 获得头像后的回调，可带一个参数接受本地头像完整路径
     */
    getUserAvatar(user, gotCallback) {
        if (!window.plus) {
            console.log("不是手机端打开，直接从服务器下载头像");

            // 给个图片的路径
            gotCallback(Config.api.download + '?attachmentId=' + user.photoUrl);

            return;
        }

        let self = this;
        // _doc/downloads/avatar/2019-05/a18883d8-2b27-44b1-8598-bed6cace59e0.jpg
        // 检查本地该用户的头像是否存在
        window.plus.io.resolveLocalFileSystemURL(
            "_doc/downloads" + user.photoUrl,
            function(entry) {
                console.log("_doc/downloads " + user.photoUrl + "存在本地，不需下载");
                // 存在
                if (gotCallback) {
                    gotCallback(entry.toRemoteURL());
                }
            },
            function(e) {
                // 不存在
                console.log("从服务器下载");
                // 从服务器上下载
                self.downloadUserAvatar(user.userId, function(task) {
                    if (gotCallback) {
                        window.plus.io.resolveLocalFileSystemURL(
                            task.filename,
                            function(entry) {
                                gotCallback(entry.toRemoteURL());
                            }
                        );
                    }
                });
            }
        );
    },

    /**
     * 下载用户头像
     * @param {*} userId 指定的用户
     * @param {*} downloadCallback 下载完成的回调
     */
    downloadUserAvatar(userId, downloadCallback) {
        Upload.typeDownload(
            Config.api.localAvatarDir,
            userId,
            "avatar",
            false,
            function(task) {
                if (downloadCallback) {
                    downloadCallback(task);
                }
            }
        );
    },

    selectImage(title, gotCallback) {
        let self = this;
        let buttons = [
            {
                title: "拍摄"
            },
            {
                title: "从相册选择"
            }
        ];
        if (plus.isWindows) {
            buttons = [
                {
                    title: "从相册选择"
                }
            ];
        }
        window.plus.nativeUI.actionSheet(
            {
                title: title,
                cancel: "取消",
                buttons: buttons
            },
            function(e) {
                if (e.index == 1) {
                    // 拍摄
                    self.cameraImage(gotCallback);
                } else if (e.index == 2) {
                    // 从相册选取
                    self.galleryImg(gotCallback);
                }
            }
        );
    },

    cameraImage(gotCallback) {
        console.log("开始拍照：");
        var filename = "_doc/" + "camera/" + Util.random() + ".jpg";
        var cmr = window.plus.camera.getCamera();
        cmr.captureImage(
            function(p) {
                console.log("成功：" + p);
                window.plus.io.resolveLocalFileSystemURL(
                    p,
                    function(entry) {
                        var path = entry.fullPath;
                        if (gotCallback) {
                            gotCallback(path, true);
                        }
                    },
                    function(e) {
                        console.error("读取拍照文件错误：" + e.message);
                    }
                );
            },
            function(e) {
                console.error("失败：" + e.message);
            },
            {
                filename: filename,
                index: 1
            }
        );
    },

    galleryImg(gotCallback) {
        console.log("从相册中选择图片：");
        window.plus.gallery.pick(
            function(path) {
                if (gotCallback) {
                    gotCallback(path, false);
                }
            },
            function(e) {
                console.log("取消选择图片");
            },
            {
                filter: "image"
            }
        );
    },

    /**
     * 清空本机当前用户头像目录
     */
    clearUserAvatarDir() {
        // 先清空头像文件夹下的头像文件
        window.plus.io.resolveLocalFileSystemURL(
            Config.api.localAvatarDir,
            function(entry) {
                console.log("删除目录的路径：" + entry.fullPath);
                entry.removeRecursively(
                    function(e) {
                        console.log("清空目录成功");
                    },
                    function(e) {
                        console.log(e.message);
                    }
                );
            }
        );
    }
});

export default user;
